<?php

namespace App\Admin\Controllers;

use App\AdminPermission;
use App\AdminRole;

class RoleController extends Controller
{

    //角色列表
    public function index()
    {
        $roles = AdminRole::paginate(10);
        return view('admin.role.index', compact('roles'));
    }

    //创建角色
    public function create()
    {
        return view('admin.role.add');
    }

    //创建角色行为
    public function store()
    {
        //验证
        $this->validate(request(), [
            'name' => 'required|min:3',
            'description' => 'required',
        ]);

        //逻辑
        $data = [
            'name' => request('name'),
            'description' => request('description')
        ];

        AdminRole::create($data);

        //渲染
        return redirect('/admin/roles');

    }

    //角色权限关系页面
    public function permission(AdminRole $role)
    {
        //获取所有权限
        $permissions = AdminPermission::all();

        //获取当前角色的权限
        $myPermissionos = $role->permissions;

        return view('admin.role.permission', compact('permissions', 'myPermissionos', 'role'));
    }

    //储存角色权限行为
    public function storePermission(AdminRole $role)
    {
        $this->validate(request(), [
            'permissions' => 'required|array'
        ]);

        $permissions = AdminPermission::find(request('permissions'));
        $myPermissions = $role->permissions;

        //增加权限
        $addPermissions = $permissions->diff($myPermissions);
        foreach ($addPermissions as $permission) {
            $role->grantPermission($permission);
        }

        //删除权限
        $deletePermissions = $myPermissions->diff($permissions);
        foreach ($deletePermissions as $permission) {
            $role->deletePermission($permission);
        }

        return back();
    }


}